<template>
    <nav class="top-nav">
        <ul class="nav-list">
            <li
                v-for="item in items"
                :key="item.id"
                :class="{ active: activeItem === item.id }"
                @click="handleClick(item.id)"
                class="nav-item"
            >
                {{ item.label }}
            </li>
        </ul>
    </nav>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue'

// 定义 props 以接收父组件传入的数据
const props = defineProps({
    items: {
        type: Array,
        required: true
    },
    initialActiveId: {
        type: Number,
        default: null
    }
})

// 定义 emits 以便发射自定义事件
const emit = defineEmits(['update:activeItem'])

// 创建响应式状态来跟踪当前激活的导航项
const activeItem = ref(props.initialActiveId)

// 监听 props.initialActiveId 的变化，并更新 activeItem
watch(() => props.initialActiveId, (newId) => {
    activeItem.value = newId
})

// 处理点击事件
function handleClick(id) {
    activeItem.value = id // 更新当前激活的项
    emit('update:activeItem', id) // 向父组件发射自定义事件，传递点击的项的 ID
}
</script>

<style scoped>
  .top-nav {
    height: 3.0625rem;
    padding-top: .375rem;
    box-sizing: border-box;
  }

  .nav-list {
    display: flex;
    list-style-type: none;
    padding: 0;
    margin: 0;
  }

  .nav-item {
    cursor: pointer;
    padding: .875rem .9375rem;
    color: #999;
    font-size: 1rem;
    line-height: 1rem;
    font-weight: 500;
  }

  .nav-item.active {
    color: #333;
  }

  /* .nav-item:not(.active) {
    color: #808080;
    background-color: transparent;
  }

  .nav-item:hover {
    background-color: #e0e0e0;
  } */
</style>
